package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 没天赋
 * @since 2025-03-11
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 关注或取关
     *
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 1.查询用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follow:" + userId;
        // 2.判断关注还是取关
        if (isFollow) {
            // 3.1.关注则添加数据库
            Follow follow = Follow.builder()
                    .userId(userId)
                    .followUserId(followUserId)
                    .build();
            boolean isSuccess = save(follow);
            // 3.2.关注成功则添加缓存到Redis
            if (isSuccess) {
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            // 4.取关则删除数据库信息 delete from follow where user_id = ? and follow_user_id = ?
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId)
                    .eq("follow_user_id", followUserId));
            if (isSuccess) {
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
        // 5.返回
        return Result.ok();
    }

    /**
     * 判断是否关注
     *
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 1.查询用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follow:" + userId;
        // 2.查询是否关注
        /*Integer count = query().eq("user_id", userId)
                .eq("follow_user_id", followUserId)
                .count();*/
        Boolean followOrNot = stringRedisTemplate.opsForSet().isMember(key, followUserId.toString());
        // 3.返回
        return Result.ok(BooleanUtil.isTrue(followOrNot));
    }

    /**
     * 共同关注功能
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        // 1.查询用户id
        Long userId = UserHolder.getUser().getId();
        String key1 = "follow:" + userId;
        String key2 = "follow:" + id;
        // 2.查询共同关注
        Set<String> ids = stringRedisTemplate.opsForSet().intersect(key1, key2);
        //如果无共同关注直接返回
        if (ids == null || ids.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 3.将ids转换为UserDTO
        List<Long> idList = ids.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> users = userService.listByIds(idList)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }
}
